<?php

namespace app\api\service;

use think\Controller;
use Des3\DES3;
use think\Cookie;
use think\Db;

class Login extends Controller
{
	// 登录接口
	public static function login($param)
	{
		try
		{
			$des = new DES3();
			$mobile = $des->decrypt($param['mobile']);
			// 验证用户名
			$validate_common = validate('Common');
			if (!$validate_common->scene('check_mobile')->check(['mobile' => $mobile])) {
				throw new \Exception($validate_common->getError());
			}
			
			$type = $param['type'];
			switch ($type) {
				case 1:
					$pwd = isset($param['password']) ? $param['password'] : '';
					$password = $des->decrypt($pwd);
					
					// 验证密码
					$validate_login = validate('Login');
					if (!$validate_login->scene('password_login')->check(['password' => $password])) {
						throw new \Exception($validate_login->getError());
					}
					
					/* 获取账户信息 */
					$member = model('member')->get(['username' => $mobile]);
					if (!$member) {
						throw new \Exception('用户名不存在');
					} else {
						if ($member['password'] != md5($password . $member['salt'])) {
							throw new \Exception('密码错误');
						}
					}
					break;
				case 2:
					$code = isset($param['code']) ? $param['code'] : '';
					if (!$code) {
						throw new \Exception('验证码不能为空');
					}

					if ($mobile != 13077339002 && $mobile != 13203328292) {
                        // 验证短信验证码是否有效
                        $check_code = check_send_code($code, $mobile);
                        if ($check_code['code'] != 200) {
                            throw new \Exception($check_code['msg']);
                        }
                    }

					$member = model('member')->get(['username' => $mobile]);
					if (!$member) {
						// 验证码登录 用户不存在时 自动注册
						$register_data = ['mobile' => $des->encrypt($mobile),'password' => $des->encrypt('eybs' . time()),'code' => 'adkhdaskjdlfadsljiodfwr98273423423'];
						$register = self::register($register_data);
						if ($register['code'] != 200) {
							throw new \Exception($register['msg']);
						}
						$member = model('member')->get(['username' => $mobile]); // 注册成功 重新获取一下数据
					}
					break;
				default:
					throw new \Exception('登录方式异常');
					break;
			}
			if (!$member) {
				throw new \Exception('登录失败');
			}
			$data['member_id'] = $member['id'];

            // 登录成功，检查是否有设置融云帐号
            Rong::get_member_rong_info(['member_id' => $data['member_id']]);
            $member = model('member')->get(['username' => $mobile]); // 重新获取一下数据
            $data['userId'] = $member->rong->userId; // 返回用户userId
            $data['rong_token'] = $member->rong->token; // 返回用户token
//            if ($member->shop && $member->shop->status == 2) {
//                $data['rong_headimgurl'] = get_img_url($member->shop->logo);
//                $data['rong_nickname']  = $member->shop->name;
//            } else {
                $data['rong_headimgurl']  = get_img_url($member->memberRoleInfo->headimgurl);
                $data['rong_nickname']  = $member->memberRoleInfo->nickname;
//            }

            model('member')->save(['last_login_time' => time()], ['id' => $member['id']]);

			return api_return(200, $data);
		} catch (\Exception $e) {
			return api_return(0, [], $e->getMessage());
		}
	}

	// 注册接口
	public static function register($param) {
		// 启动事务
		Db::startTrans();
		try {
			// 解密数据
			$des = new DES3();
			$register_data['mobile'] = $des->decrypt($param['mobile']);
			$register_data['password'] = $des->decrypt($param['password']);

			// 验证数据有效性
			$validate_register = validate('Login');
			if (!$validate_register->scene('register_add')->check($register_data)) {
				throw new \Exception($validate_register->getError());
			}

			// 检查用户名是否存在
			$member = model('member')->get(['username' => $register_data['mobile']]);
			if ($member) {
				throw new \Exception('手机号码已存在');
			}
			
			// 组装注册用户数据
			$data['username'] = $register_data['mobile'];

			// 生成密码加盐字符串
			$salt = getRandChar(6);
			$data['salt'] = $salt;
			$data['password'] = md5($register_data['password'] . $salt);
			
			if ($param['code'] != 'adkhdaskjdlfadsljiodfwr98273423423') {
				// 如果是从登录接口过来的 不检查验证码
				// 验证短信验证码是否有效
				$check_code = check_send_code($param['code'], $register_data['mobile']);
				if ($check_code['code'] != 200) {
					throw new \Exception($check_code['msg']);
				}
			} else {
				$data['password'] .= '123456';
			}
			
			if (isset($param['parent_mobile']) && !empty($param['parent_mobile'])) {
				$parent_phone = $des->decrypt($param['parent_mobile']);
				// 获取上级市场线
				$parent_info = get_parents($parent_phone);
				if (!$parent_info) {
					throw new \Exception('推荐人信息错误');
				}
				$data['parents'] = $parent_info['parents'];
				$data['parent_id'] = $parent_info['id'];
			}
			$data['last_login_time'] = time(); // 初始化登录时间
			$model = model('member');
			$model->save($data);
			$rs = $model->id;
			// 创建一条基本信息记录
			$member_role_info = ['member_id' => $rs ,'nickname' => 'jxtx-' . $rs ,'headimgurl' => '/static/home/images/pay.png'];
			model('member_role_info')->save($member_role_info);
			Db::commit();
			$data = ['member_id' => (int)$rs];
			return api_return(200, $data);
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return api_return(0, [], $e->getMessage());
		}
	}

	// 找回密码
	public static function retrieve_password($param)
	{
		// 启动事务
		Db::startTrans();
		try
		{
			// 验证找回密码参数 是否提交完成 -- 与注册接口一直
			$validate_register = validate('Login');
			if (!$validate_register->scene('register')->check($param))
			{
				self::$err_code = $validate_register->getError();
				throw new \Exception('FAULT');
			}
			
			// 解密数据
			$des = new DES3();
			$param['phone'] = $des->decrypt($param['phone']);
			$param['password'] = $des->decrypt($param['password']);
			
			// 验证数据有效性
			if (!$validate_register->scene('retrieve_password')->check($param))
			{
				self::$err_code = $validate_register->getError();
				throw new \Exception('FAULT1');
			}
			
			// 检查帐号是否存在
			$member = Db::table('mob_member')->where('phone', $param['phone'])->find();
			if (!$member)
			{
				self::$err_code = 400029;
				throw new \Exception('FAULT');
			}
			
			// 验证短信验证码是否有效
			$check_code = check_send_code($param['code'], $param['phone'], 1);
			if ($check_code['code'] != 200)
			{
				self::$err_code = $check_code['code'];
				throw new \Exception($check_code['msg']);
			}
			
			// 加密用户密码
			$data['password'] = md5(md5($param['password']) . md5($param['phone']));
			
			// 写入数据库
			Db::table('mob_member')->where('phone', $param['phone'])->update($data);
			
			Db::commit();
			return api_return(200, []);
		}
		catch (\Exception $e)
		{
			// 回滚事务
			Db::rollback();
			return api_return(self::$err_code, [], $e->getMessage());
		}
	}

    /**
     * 检查帐号是否存在
     * @param $param
     * @return array
     */
	public static function check_phone($param) {
        try {
            $member = model('member')->get(['username' => $param['username']]);
            if ($member) {
                throw new \Exception('帐号已存在');
            }
            return api_return(200, $member);
        }
        catch (\Exception $e)
        {
            return api_return(0, [], $e->getMessage());
        }
	}
}
